<?php

namespace App\Repository\UpThree;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Api\Transfer;
use Hamcrest\Type\IsString;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use App\Repository\BaseRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Product\ProductRepository;
use App\Repository\Order\OrderProductRepository;
use App\Repository\Order\OrderChannelRepository;
use Illuminate\Support\Facades\Cache;
use App\Repository\GetWay\WayRepository;
use App\Repository\Order\OrderRepository;

class ThreeOrderRepository extends BaseRepository
{
    public function __construct(GoodsRepository $GoodsRepository, ProductRepository $ProductRepository, OrderProductRepository $OrderProductRepository, OrderChannelRepository $OrderChannelRepository, OrderRepository $OrderRepository)
    {
        $this->goodsModel = $GoodsRepository;
        $this->productModel = $ProductRepository;
        $this->orderProductModel = $OrderProductRepository;
        $this->channelModel = $OrderChannelRepository;
        $this->orderModel = $OrderRepository;
        $this->log = new Logger('ChinnelLog');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        // 记录的是 第三方成功了 但是本地失败了 
        $this->logOrder = new Logger('orderLogs');
        $this->logOrder->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/orderLogs.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }
    // 查询号码
    public function selectNum($data = array())
    {
    }
    // 下单统一调用接口
    public function orderSubmit($data = array())
    {
        // var_dump(time());
        if (empty($data['goods_id']) && (empty($data['goods_code']) || empty($data['shop_id']))) {
            return $this->returnMsg(10001, '商品信息不能为空');
        }
        // if (empty($data['shop_id'])) {
        //     return $this->returnMsg(2, '店铺信息不能为空');
        // }
        if (empty($data['name'])) {
            return $this->returnMsg(1, '用户名不能为空');
        }
        $name = strip_tags(trim($data['name']));
        $len = mb_strlen($name);
        if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·?]?[\x{4e00}-\x{9fa5}]+$/u', $name, $matchers)) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }
        if ($len < 2 || $len > 10) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }

        //判断手机号
        if (empty($data['contact'])) {
            return $this->returnMsg(10007, '请输入您的手机号码');
        }
        if (!preg_match("/^1[3456789]\d{9}$/", $data['contact'])) {
            return $this->returnMsg(10007, '手机号错误，请重新查看');
        }
        if (empty($data['province'])) {
            return $this->returnMsg(10010, '缺少省份');
        }
        if (empty($data['city'])) {
            return $this->returnMsg(10011, '缺少市');
        }
        // if (!$request->has('area')) {
        //     return $this->returnMsg(10012, '缺少区');
        // }

        // $province = strip_tags(trim($data['province']));
        // $city = strip_tags(trim($data['city']));


        if (empty($data['address'])) {
            return $this->returnMsg(10013, '详细地址不能为空');
        }
        $lens = mb_strlen($data['address']);
        if (getStrLen($data['address']) < 4 || $lens > 50) {
            return $this->returnMsg(10006, '详细地址内容不小于4个汉字，请重新输入');
        }
        // 提交过来的字符串处理
        $data['identity'] = strtoupper(trim($data['identity'], ''));
        $data['address'] = (trim($data['address'], ''));
        $data['contact'] = (trim($data['contact'], ''));
        $data['name'] = (trim($data['name'], ''));
        $params['address'] = $data['address'];
        if (empty($data['identity'])) {
            return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
        }
        $idcard = $data['identity'];

        if (!is_idcard($idcard)) {
            return $this->returnMsg(10007, '身份证号码不正确，请检查');
        }

        $data['orderno'] = creatOrderNums('Hk_');
        // 使用缓存防止重复提交 或 重复记录数据
        $resCache = Cache::get($idcard . '_' . $data['contact']);
        $oneAdress = Cache::get($idcard . '_' . $data['contact'] . '_address');
        if (!empty($resCache) && ($oneAdress == $data['address'])) {
            if ($resCache == $data['address']) {
                return $this->returnMsg(101, '请稍后提交,查看是否是否提交成功');
            }
            // return  $this->returnMsg(102, $resCache);
        }
        Cache::put($idcard . '_' . $data['contact'], $data['address']);
        Cache::put($idcard . '_' . $data['contact'] . '_address', $data['address']);
        // 参数验证完了
        $msg = '未查询到下单';
        $flag = true;
        //商品验证
        $whereGoods = [];
        if (!empty($data['goods_id'])) {
            $whereGoods['id'] = $data['goods_id'];
        }
        if (!empty($data['goods_code']) && !empty($data['shop_id'])) {
            $whereGoods['goods_code'] = $data['goods_code'];
            $whereGoods['shop_id'] = $data['shop_id'];
        }
        $resGoods = $this->goodsModel->getOne($whereGoods, ['id', 'name', 'goods_code', 'product_name', 'product_id', 'product_code', 'shop_str']);
        if (!$resGoods) {
            $flag = false;
            $msg = '未查询到商品信息';
        }
        $insertData = [];
        if ($flag) {
            // 添加还是修改 为了存储信息
            $insertData = [
                'orderno' => $data['orderno'],
                'dist_orderno' => !empty($data['dist_orderno']) ? $data['dist_orderno'] : '',
                'dist_id' => !empty($data['dist_id']) ? $data['dist_id'] : 0,
                'dist_name' => !empty($data['dist_name']) ? $data['dist_name'] : '',
                'contact_phone' => !empty($data['contact_phone']) ? $data['contact_phone'] : $data['contact'],
                'contact_name' => !empty($data['contact_name']) ? $data['contact_name'] : $data['name'],
                'pay_name' => $data['name'],
                'pay_phone' => $data['contact'],
                'pay_identity' => $idcard,
                'post_province' => !empty($data['province']) ? $data['province'] : '',
                'post_city' => !empty($data['city']) ? $data['city'] : '',
                'post_area' => !empty($data['area']) ? $data['area'] : '',
                'post_address' => !empty($data['address']) ? $data['address'] : '',
                'status' => 1,
                'shop_id' => $data['shop_id'],
                'shop_str' => $resGoods['shop_str'],
                'goods_id' => $resGoods['id'],
                'goods_name' => $resGoods['name'],
                'goods_code' => $resGoods['goods_code'],
                'product_id' => $resGoods['product_id'],
                'product_name' => $resGoods['product_name'],
                'product_code' => $resGoods['product_code'],
            ];
        }
        // 产品验证开始
        $productId = !empty($resGoods->product_id) ? $resGoods->product_id : 0;
        // var_dump($productId, 222222222);
        if ($flag) {
            $resProduct = $this->validProduct($productId, $data);
            // var_dump($resProduct);
            if (empty($resProduct['code']) || $resProduct['code'] != 200) {
                $flag = false;
                $msg = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
            }
            $insertData['sup_orderno'] = !empty($resProduct['data']['order_id']) ? $resProduct['data']['order_id'] : ''; //渠道单号
            $insertData['sup_id'] = !empty($resProduct['data']['channel_id']) ? $resProduct['data']['channel_id'] : ''; //渠道id
            $insertData['sup_name'] = !empty($resProduct['data']['channel_name']) ? $resProduct['data']['channel_name'] : ''; //渠道名称
            $insertData['three_msg'] = !empty($resProduct['data']['msg']) ? $resProduct['data']['msg'] : '';
            $insertData['channel_error_josn'] = !empty($resProduct['data']['error']) ? $resProduct['data']['error'] : '';
        }
        // 下单流程
        if ($flag) {
            $resOrder = $this->orderModel->add($insertData);
            if (empty($resOrder['code']) || $resOrder['code'] != 200) {
                //第三方提交成功了 但是存储数据库的时候 失败了 记录日志文件方便查看
                $this->logOrder->info('参数:' . json_encode($insertData) . '返回参数:' . json_encode($resOrder));
            }
        }
        // var_dump(time());
        if ($flag) {
            Cache::put($idcard . '_' . $data['contact'], '您已下过单,请更新信息在下单');
            return $this->returnMsg(200, '下单成功');
        }
        // 防止用户长时间提交
        Cache::put($idcard . '_' . $data['contact'], $msg);
        return $this->returnMsg(100, $msg);
    }

    // 记录提交失败的订单 记录 直接插入 以 text方式记录 就行
    public function errorOrder()
    {
    }
    // 验证信息 失败 如何处理 这个地方可以添加验证  
    // 到提交到第三方的也可以 提交验证 
    // 商品参数效验
    public function validGoods_back($goodsId, $data)
    {
        $productId = 0;
        $this->validProduct($productId, $data);
    }
    //产品效验
    public function validProduct($productId, $data)
    {
        if (empty($productId)) {
            return $this->returnMsg(3, '产品信息不能为空');
        }
        $resProduct = $this->productModel->getOne(['id' => $productId]);
        if (!$resProduct) {
            return $this->returnMsg(4, '未查询到产品信息');
        }
        // 产品所有的信息 验证
        // var_dump($resProduct, 2222222222);
        // 年龄限制
        $age = getAgeByID($data['identity']);
        if ($age > $resProduct->limit_max_age || $age < $resProduct->limit_min_age) {
            return $this->returnMsg(5, "很抱歉，用户年龄需要在{$resProduct->limit_min_age}～{$resProduct->limit_max_age}才可下单");
        }
        //开卡限制
        //单人开卡数量限制
        if (!empty($resProduct->max_number)) {
            $where = [];
            if (!empty($resProduct->cycle)) {
                $time = date('Y-m-d 00:00:00', strtotime("-$resProduct->cycle month"));
                $where[] = ['created_at', '>=', $time];
            }

            $where[] = ['idcard', '=', $data['identity']];
            $count = $this->orderProductModel->getCount($where);
            if ($resProduct->max_number <= $count) {
                return $this->returnMsg(4, '开卡数量超过限制');
            }
        }
        // 提交到第三方
        $channelData = [
            'product_code' => $resProduct->product_code,
            'product_id' => $resProduct->id,
            'is_charm' => $resProduct->is_charm,
            'shop_id' => $resProduct->shop_id,
        ];
        $resChannel = $this->moreChannel($channelData, $data);
        return $resChannel;
    }
    public function moreChannel($jsonData, $data)
    {
        $where = [
            'shop_id' => $jsonData['shop_id'],
            'product_id' => $jsonData['product_id']
        ];
        $resChannel = $this->channelModel->getAllProduct($where);
        // if (empty(json_decode(json_encode($resChannel), true))) {
        if (empty($resChannel)) {
            return $this->returnMsg(10, '未查询到关联的通道');
        }
        $returnMsg = [];
        $jsonReturn = [];
        foreach ($resChannel as $key => $v) {
            $data['model'] = $v['channel_id'];
            $data = $this->getWay($data);
            if (empty($jsonData['is_charm'])) {
                $resCheck = $this->orderSubmitThree('checkOrder', $data);
                if (empty($resCheck['code']) || $resCheck['code'] != 200) {
                    $returnMsg = $resCheck;
                    $jsonReturn[] = [
                        'channel_id' => $v['channel_id'],
                        'channel_name' => $v['channel_name'],
                        'msg' => $resCheck['msg']
                    ];
                    continue;
                }
            }
            $returnMsg = $this->orderSubmitThree('orderSubmit', $data);
            if (empty($returnMsg['code']) || $returnMsg['code'] != 200) {
                // $returnMsg = $resSubmit;
                $jsonReturn[] = [
                    'channel_id' => $v['channel_id'],
                    'channel_name' => $v['channel_name'],
                    'msg' => $returnMsg['msg']
                ];
                continue;
            }
            $returnMsg['data']['channel_id']  = $v['channel_id'];
            $returnMsg['data']['channel_name'] = $v['channel_name'];
            break;
        }
        $returnMsg['data']['error'] = json_encode($jsonReturn);
        return $returnMsg;
    }
    //第三方的统一调用
    public function orderSubmitThree($method, $data)
    {
        $model = new Transfer();
        return $model->$method($data);
    }
    // 查询通道参数
    public function getWay($data)
    {
        // 查询单个通道
        $model = new WayRepository();
        $resChannelModel = $model->getOne(['id' => $data['model']]);
        if (!$resChannelModel) {
            return $this->returnMsg(102, '通道不存在');
        }
        $data['path'] = $resChannelModel->path;
        $data['url'] = $resChannelModel->url;
        $data['parame'] = $resChannelModel->parame;
        return $data;
    }
    // 暂时没用
    public function three($v)
    {
        $data = [];
        $this->orderSubmitThree($v, $data);
    }
}
